
package com.example.gorannet;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class login extends Activity
{
    // protected static final Context Context;
    private BootstrapButton buttonCancel;

    private BootstrapButton buttonLogin;
    private JSONObject product;
    private AlertDialogManager alert             = new AlertDialogManager();

    private BootstrapEditText editTextUsername, editTextPassword;

    private static final String           login_url        = "http://db.gorannet.net/DB/Technical/tickets/android_login.php";
    private static final String TAG_SUCCES = "success";
    private static final String TAG_CHECK = "check";
    //private static final String TAG_USERNAME = "username";
    private static final String TAG_PASSWORD = "password";
    private String dd;
    private ProgressDialog pDialog;
    private String tempPassword;
    private ConnectionDetector cd;


    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();


    ArrayList<HashMap<String, String>> productsList;
    JSONArray products = null;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        productsList = new ArrayList<HashMap<String, String>>();
        buttonCancel = (BootstrapButton)findViewById(R.id.cancelBtn);
        buttonLogin = (BootstrapButton)findViewById(R.id.loginBtn);
        //buttonLogin.setLeftIcon("fa-lemon-o");
        //buttonCancel.setLeftIcon("fa-trophy");
        editTextUsername = (BootstrapEditText)findViewById(R.id.userText);
        editTextUsername.setText("test4");
        editTextPassword = (BootstrapEditText)findViewById(R.id.passText);
        editTextPassword.setText("%100test");//asdfg hardy12345
        cd = new ConnectionDetector(getApplicationContext());

        buttonLogin.setOnClickListener(new View.OnClickListener() {
            Class<?> device = null;
            Class<MyListItems> tablet = MyListItems.class;
            Class<MyChoicesActivity> mobile = MyChoicesActivity.class;
            @Override
            public void onClick(View v) {

                boolean deviceType = isTablet(getApplicationContext());
                if(deviceType == false){
                    device = mobile;
                }else
                    if(deviceType == true)
                    {
                        device = tablet;
                    }
                DBHandler dbHandler = new DBHandler(getApplicationContext());
                try
                {
                    if (cd.isConnectingToInternet())
                    {
                        dd = md5(editTextPassword.getText().toString());
                        if (dbHandler.authenticateUser(editTextUsername.getText().toString(), dd))
                        {
                            dbHandler.updateLoginCount("0", editTextUsername.getText().toString());
                            Intent intent = new Intent(login.this, device);
                            startActivity(intent);
                        }
                        else
                        {
                            dd = md5(editTextPassword.getText().toString());


                            new GetProductDetails().execute();
                            if (dd.equals(tempPassword))
                            {
                                try
                                {
                                    dbHandler.insertAuthentication(editTextUsername.getText().toString(),dd, "0");
                                    Intent intent = new Intent(login.this, device);
                                    startActivity(intent);
                                }
                                catch(SQLiteException e)
                                {
                                    Toast.makeText(getApplicationContext(), "Try Again", Toast.LENGTH_LONG).show();
                                }
                            }
                            else
                            {
                                alert.showAlertDialog(getApplicationContext(), "Warning",
                                        "Invalid Username Or Password!", false);
                            }
                        }
                    }
                }
                catch(Exception e)
                {
                    Toast.makeText(getApplicationContext(), "Try Again", Toast.LENGTH_LONG).show();
                }
                try{
                    if (!cd.isConnectingToInternet())
                    {
                        dd = md5(editTextPassword.getText().toString());
                        if (dbHandler.authenticateUser(editTextUsername.getText().toString(), dd))
                        {

                            String countLin = dbHandler.getLoginCount(editTextUsername.getText().toString(), dd);
                            int loginCount = Integer.parseInt(countLin);
                            if (loginCount<5)
                            {
                                ++loginCount;
                                dbHandler.updateLoginCount(loginCount+"", editTextUsername.getText().toString());
                                Intent intent = new Intent(login.this, device);
                                startActivity(intent);
                            }
                            else if (loginCount >=5)
                            {
                                alert.showAlertDialog(getApplicationContext(), "Warning",
                                        "You reached max offline login!! Connect To internet to login!", false);
                            }
                        }
                        else
                        {
                            alert.showAlertDialog(getApplicationContext(), "Warning",
                                    "Invalid Username Or Password!", false);
                        }
                    }
                }
                catch(Exception e)
                {
                    Toast.makeText(getApplicationContext(), "Please Connect to Internert", Toast.LENGTH_LONG).show();
                }
            }
        });
        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem)
    {
        switch (menuItem.getItemId())
        {
            case R.id.registration:
                alert.showAlertDialog(getApplicationContext(), "Warning",
                        "You have to Login!", false);
                return true;
            default:
                return super.onOptionsItemSelected(menuItem);
        }
    }

    //Determines If The Device is Tablet?!.....If it is Tablet it returns true
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public static final String md5(final String s) {
        final String MD5 = "MD5";
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest
                    .getInstance(MD5);
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuilder hexString = new StringBuilder();
            for (byte aMessageDigest : messageDigest) {
                String h = Integer.toHexString(0xff & aMessageDigest);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }



    class GetProductDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(login.this);
            pDialog.setMessage("Loading product details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting product details in background thread
         * */
        @Override
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> param = new ArrayList<NameValuePair>();
                        param.add(new BasicNameValuePair("username", editTextUsername.getText().toString()));
                        param.add(new BasicNameValuePair("mdpass", dd));
                        JSONObject json = jParser.makeHttpRequest(login_url, "POST", param);
                        // json success tag
                        success = json.getInt(TAG_SUCCES);

                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json.getJSONArray(TAG_CHECK); // JSON Array
                            // get first product object from JSON Array
                            product = productObj.getJSONObject(0);
                            tempPassword = product.getString(TAG_PASSWORD);
                        }else{
                            alert.showAlertDialog(getApplicationContext(), "Warning",
                                    "Process not success!", false);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }


        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }
}
